﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.IO;
using mjRegister.Entity;
using System.Xml;

namespace mjRegister.BAL
{
    //组件
    public class App
    {
        //写入组件数据到文件，作为下次读取之缓存。
        public static void Init(IList<AppInfo> appInfos)
        {
            string appFile = GetAppFile();
            string appTempFile = GetAppTempFile();

            if (File.Exists(appTempFile))
                File.Delete(appTempFile);

            XElement xmlApps = new XElement("Apps");
            for (int j = 0; j < appInfos.Count; j++)
            {
                AppInfo appInfo = appInfos[j];
                xmlApps.Add(new XElement("App",
                    new XElement("AddCount", appInfo.AddCount.ToString()),
                    new XElement("Author", appInfo.Author),
                    new XElement("Description", appInfo.Description.ToString()),
                    new XElement("Id", appInfo.Id.ToString()),
                    new XElement("Img", appInfo.Img.ToString()),
                    new XElement("Name", appInfo.Name.ToString())
                   )
                );
            }

            using (XmlTextWriter writer = new XmlTextWriter(appTempFile, Encoding.UTF8))
                xmlApps.WriteTo(writer);

            if (File.Exists(appFile))
                File.Delete(appFile);

            File.Move(appTempFile, appFile);
        }

        //从文件中获取车市数据
        public static IList<AppInfo> GetAppInfos()
        {
            IList<AppInfo> appInfos = new List<AppInfo>();

            if (File.Exists(GetAppFile()))
            {
                XDocument xmlApp = XDocument.Load(GetAppFile());

                var xmlApps = xmlApp.Root.Elements("App");

                int index = 0;
                foreach (XElement xnApp in xmlApps)
                {
                    appInfos.Add(new AppInfo
                    {
                        AddCount = int.Parse(xnApp.Element("AddCount").Value),
                        Author = xnApp.Element("Author").Value,
                        Description = xnApp.Element("Description").Value,
                        Id = xnApp.Element("Id").Value,
                        Img = xnApp.Element("Img").Value,
                        Name = xnApp.Element("Name").Value
                    });
                }
            }
            return appInfos;
        }

        private static string GetAppFile()
        {
            return Path.Combine(Common.GetConfigPath(), "app.xml");
        }

        private static string GetAppTempFile()
        {
            return Path.Combine(Common.GetConfigPath(), string.Format("{0}_app_temp.xml", Guid.NewGuid().ToString()));
        }
    }
}
